package com.hmdp.utils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 生成订单号
 */
@Component
public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;

    //标准时间(开始时间戳)
    private static  final long BEGIN_TIMESTAMP = 1640995200;
    private static final int COUNT_BITS = 32;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix){
        //1.生成时间戳
        //当前时间
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        //将当前时间的毫秒值-标准时间的毫秒值得到时间戳 timestamp
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        //2.生成序列号
        //获取当前日期,精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        //自增长
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + timestamp + ":" + date);

        //3.拼接并返回
        //一共64位 符号位(0)  -------  时间戳(31) -----------序列号 (32)--------------
        //将时间戳向右移动32位到高位,把低位让出来给序列号
    return timestamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        //标准时间
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        //转换成秒数
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(second);
    }
}
